package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.bean.User;
import com.example.reggie.dto.UserDto;
import com.example.reggie.service.UserService;
import com.example.reggie.utils.R;
import com.example.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/getCode")
    public R<String> getCode(String phone, HttpSession session){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        session.setAttribute(phone,code);
        System.out.println("code="+code);
        return R.success("获取验证码成功");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto user,HttpSession session){
        String phone=user.getPhone();
        String code=user.getCode();
        if (code.equals(session.getAttribute(phone))){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User userInfo=userService.getOne(queryWrapper);
            if (userInfo==null){
                user.setStatus(1);
                userService.save((User) user);
                session.setAttribute("user",user.getId());
            }else{
                userInfo.setStatus(1);
                userService.updateById(userInfo);
                session.setAttribute("user",userInfo.getId());
            }
            return R.success("登录成功");
        }
        throw new RuntimeException("验证码不正确登录失败");
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        UserDto user=(UserDto) session.getAttribute("user");
        if (user!=null){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,user.getPhone());
            User userInfo=userService.getOne(queryWrapper);
            userInfo.setStatus(1);
            userService.updateById(userInfo);
            session.removeAttribute("user");
        }

        return R.success("退出登录成功");
    }
}
